package com.kfm.pm.udp;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class Server {

    public static void main(String[] args) {
        System.out.println("服务端启动成功....");
        try {
            DatagramSocket socket = new DatagramSocket(8888);
            Scanner sc = new Scanner(System.in);
            while (true) {
                byte[] bytes = new byte[1024 * 64];
                DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);
                // 接受信息存储到 packet 中
                try {
                    socket.receive(packet);
                } catch (IOException e) {
                    System.out.println("服务端异常");
                    break;
                }
                int len = packet.getLength();
                String message = new String(bytes, 0, len);
                // 在服务端 通过 packet.getAddress() 可以获取发送数据包的IP对象
                System.out.println(packet.getAddress().getHostAddress() + " say " + message);
                System.out.println("你说：");
//                String receive = sc.next();
//                byte[] bytes1 = receive.getBytes();
//                DatagramPacket packet1 = new DatagramPacket(bytes1, 0, bytes1.length, packet.getAddress(), packet.getPort());
//                socket.send(packet1);
            }
        } catch (SocketException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
